<template>
  <div class="home">
    <div class="sidebar">
      <!-- 标题 -->
      <div class="sidebar-title">AI问答</div>
      <!-- 按钮 -->
      <button class="sidebar-btn" @click="createSession">新建对话</button>
      <!-- 对话列表 -->
      <div class="session-list">
        <div class="session-item" :class="{ 'active': item.sessionId === currentSessionId }"
          v-for="item in sessionList" :key="item.sessionId" @click="getMessages(item.sessionId)">
          <span class="session-text">{{ item.sessionName }}</span>
          <span class="delete-icon" @click.stop="deleteSession(item.sessionId)" title="删除会话">✕</span>
        </div>
      </div>
    </div>
    <!-- z著区域 -->
    <div class="main-container">
      <main class="main-content">
        <div class="model-selector">
          <label for="model-select">使用模型：</label>
          <select id="model-select" v-model="selectedModel" class="model-select">
            <option value="qwen-Plus-Latest">qwen-plus-latest</option>
            <option value="deepSeek-V3.1">deepseek-v3.1</option>
          </select>
        </div>

        <div class="chat-container" ref="chatContainer">
          <div v-if="messagesList.length === 0" class="empty-state">
            <h3>开始对话吧！</h3>
            <p>输入你的问题，AI助手会为您提供解答</p>
          </div>
          <div v-for="message in messagesList" :key="message.messageId" :class="[
            'message',
            message.messageType === 'user' ? 'user' : 'ai',
          ]">
            <div v-html="message.content"></div>
          </div>
          <div v-if="isTyping" class="message ai-message">
            <div>思考中...</div>
            <div class="loading"></div>
          </div>
        </div>

        <div class="input-container">
          <input class="input-field" type="text" v-model="inputMessage" @keyup.enter="sendMessage"
            placeholder="输入你的问题..." :disabled="isTyping" />
          <button class="send-button" @click="sendMessage" :disabled="!inputMessage.trim() || isTyping">
            发送
          </button>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getSessionListApi,
  saveSessionApi,
  saveMessageApi,
  deleteSessionApi,
  getMessagesApi,
} from "../request/ai";

// 历史会话列表
let sessionList = ref<Array<{ sessionId: string; sessionName: string }>>([]);

// 获取会话列表
async function getSessionList() {
  try {
    const res = await getSessionListApi();
    sessionList.value = res.data;
  } catch (error) {
    console.error("获取会话列表失败:", error);
    throw error;
  }
}

// 删除会话
async function deleteSession(sessionId: string) {
  try {
    await deleteSessionApi(sessionId);
    getSessionList();
    if(currentSessionId.value==sessionId){
      currentSessionId.value = '';
      messagesList.value = [];
    }
  } catch (error) {
    console.error("删除会话失败:", error);
    throw error;
  }
}

// 选择的模型
let selectedModel = ref<string>("qwen-Plus-Latest");

// 对话消息列表
let messagesList = ref<
  Array<{
    messageId: string;
    sessionId: string;
    content: string;
    messageType: string;
    create_time?: string;
  }>
>([]);

let currentSessionId = ref<string>("");

// 获取消息列表
async function getMessages(sessionId: string) {
  try {
    const res = await getMessagesApi(sessionId);
    messagesList.value = res.data;
    currentSessionId.value = sessionId;
  } catch (error) {
    console.error("获取消息列表失败:", error);
    throw error;
  }
}

let inputMessage = ref<string>("");
let isTyping = ref<boolean>(false);

// 发送消息 前端主动保存会话,后端保存问答记录
async function sendMessage() {
  if (!inputMessage.value.trim()) return;

  // 如果是新会话，先保存会话
  if (!currentSessionId.value) {
    // 保存新会话
    let saveSessionResult = await saveSessionApi(
      inputMessage.value,
    );
    currentSessionId.value = saveSessionResult.data.sessionId;
    // 刷新会话列表
    getSessionList();
  }

  // 保存当前提问信息
  let saveMessageResult = await saveMessageApi(currentSessionId.value, "user", inputMessage.value);
  if (saveMessageResult.success === true) {
    await getMessages(currentSessionId.value);
  }

  let aiMessageId = 'msg_' + new Date().getTime();
  // 添加一条ai消息占位
  messagesList.value.push({
    messageId: aiMessageId,
    sessionId: currentSessionId.value,
    content: '',
    messageType: 'ai',
  })

  const url = `/api/chat?message=${inputMessage.value}&modelName=${selectedModel.value}&sessionId=${currentSessionId.value}&messageId=${aiMessageId}`;

  const eventSource = new EventSource(url)
  isTyping.value = true;
  inputMessage.value = "";

  eventSource.onmessage = (event) => {

    if (event.data === "[-end-]") {
      isTyping.value = false;
      eventSource.close();
      return;
    }
    let data = JSON.parse(event.data);

    // 更新内容
    const lastMessage = messagesList.value[messagesList.value.length - 1];
    if (lastMessage) {
      lastMessage.content += data.content;
    }
  }

  eventSource.onerror = (error) => {
    console.error("服务错误:", error);
    isTyping.value = false;
    eventSource.close();
  };
}

// 新建对话
function createSession() {
  currentSessionId.value = '';
  messagesList.value = [];
  inputMessage.value = '';
}



onMounted(() => {
  // 初始获取会话列表
  getSessionList();
});
</script>

<style scoped lang="less">
.home {
  width: 100%;
  height: 100%;
  display: flex;
}

.sidebar {
  width: 288px;
  height: 100%;
  // padding: 10px;
  background-color: #f8f9fa;
  border-right: 1px solid #e0e0e0;
  text-align: center;
  display: flex;
  flex-direction: column;

  .sidebar-title {
    font-size: 24px;
    font-weight: bold;
    color: #000000;
    padding: 10px;
  }

  .sidebar-btn {
    width: 230px;
    height: 38px;
    line-height: 38px;
    background-color: #499ef8;
    border-radius: 20px;
    font-size: 16px;
    font-weight: bold;
    color: #ffffff;
    margin: 10px auto 20px;
    border: 0;
    cursor: pointer;

    &:hover {
      background-color: #3992f3;
    }
  }

  .session-list {
    border-top: 1px solid #e0e0e0;
    flex: 1;
    padding: 10px 8px 10px 12px;
    margin: 0 5px;
    overflow: auto;

    .session-item {
      padding: 10px 6px;
      margin-bottom: 8px;
      cursor: pointer;
      transition: all 0.2s;
      font-size: 14px;
      text-align: left;
      position: relative;
      display: flex;
      align-items: center;

      &:hover {
        color: #499ef8;
        background-color: #f0f0f0;
      }

      &.active {
        background-color: #e6f0ff;
        font-weight: bold;
        color: #499ef8;
      }

      .session-text {
        width: 90%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .delete-icon {
        position: absolute;
        right: 8px;
        opacity: 0;
        transition: opacity 0.2s;
        color: #666;
        font-size: 12px;
        cursor: pointer;

        &:hover {
          color: #ff4d4f;
          font-weight: bold;
        }
      }

      &:hover .delete-icon {
        opacity: 1;
      }
    }
  }
}

.main-container {
  flex: 1;
  height: 100%;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .main-content {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background-color: #fff;
    display: flex;
    flex-direction: column;

    // 模型选择
    .model-selector {
      .model-select {
        padding: 8px 12px;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        background-color: #fff;
        font-size: 14px;
        color: #333;
        cursor: pointer;
        transition: all 0.3s ease;
        outline: none;
        min-width: 180px;

        &:hover {
          border-color: #ffffff;
          background-color: #f8f9ff;
        }

        &:focus {
          border-color: #ffffff;
          border: 1px solid #e0e0e0;
        }

        option {
          padding: 10px;
          background-color: #fff;
          color: #333;
          cursor: pointer;

          &:hover {
            background-color: #f8f9ff;
          }
        }
      }
    }

    // 对话区域
    .chat-container {
      flex: 1;
      max-height: calc(100vh - 100px);
      overflow-y: auto;
      padding: 15px;
      background-color: #f9f9f9;
      border-radius: 8px;
      margin: 15px 0;
      display: flex;
      flex-direction: column;

      .empty-state {
        text-align: center;

      }

      // 消息样式
      .message {
        margin-bottom: 15px;
        padding: 6px 12px;
        border-radius: 12px;
        width: auto;
        max-width: 70%;
        word-wrap: break-word;

        &.user {
          background-color: #499ef8;
          color: white;
          align-self: flex-end;
        }

        &.ai {
          background-color: #ececec;
          align-self: flex-start;
        }

        &.ai-message {
          padding: 4px 12px;
          display: flex;
          align-items: center;
          gap: 10px;
          font-size: 14px;
        }

        // 加载
        .loading {
          display: inline-block;
          width: 16px;
          height: 16px;
          border: 2px solid #f3f3f3;
          border-top: 2px solid #3498db;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }

        @keyframes spin {
          0% {
            transform: rotate(0deg);
          }

          100% {
            transform: rotate(360deg);
          }
        }
      }

      // 空消息提示
      .empty-message {
        font-size: 14px;
        color: #999;
        text-align: center;
        padding: 20px;

        h3 {
          margin: 0 0 10px 0;
          color: #333;
        }

        p {
          margin: 0;
          font-size: 14px;
        }
      }
    }

    // 输入框和发送按钮
    .input-container {
      display: flex;
      gap: 10px;
      padding: 10px 0;

      .input-field {
        flex: 1;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 20px;
        font-size: 14px;
        outline: none;
        transition: border-color 0.2s;

        &:focus {
          border-color: #2196f3;
        }
      }

      .send-button {
        padding: 10px 20px;
        background-color: #2196f3;
        color: white;
        border: none;
        border-radius: 20px;
        font-size: 14px;
        cursor: pointer;
        transition: background-color 0.2s;

        &:hover:not(:disabled) {
          background-color: #1976d2;
        }

        &:disabled {
          background-color: #ccc;
          cursor: not-allowed;
        }
      }
    }
  }
}
</style>